﻿using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;

namespace 加密算法
{
    public class DSAHelper
    {
        /// <summary>
        /// 生成RSA密钥对
        /// </summary>
        /// <param name="keySize"></param>
        /// <returns></returns>
        public static AsymmetricCipherKeyPair GenerateDSAKeyPair()
        {
            var curve = ECNamedCurveTable.GetByName("secp256r1"); // 使用一个常用的椭圆曲线
            var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H);
            var keyGenerationParameters = new ECKeyGenerationParameters(domainParams, new SecureRandom());
            var keyPairGenerator = new ECKeyPairGenerator();
            keyPairGenerator.Init(keyGenerationParameters);
            return keyPairGenerator.GenerateKeyPair();
        }
        /// <summary>
        /// 签名
        /// </summary>
        /// <param name="message"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        public static byte[] SignDSA(byte[] message, AsymmetricKeyParameter privateKey)
        {
            var signer = SignerUtilities.GetSigner("SHA-256withECDSA");
            signer.Init(true, privateKey);
            signer.BlockUpdate(message, 0, message.Length);
            return signer.GenerateSignature();
        }
        /// <summary>
        /// 验证
        /// </summary>
        /// <param name="message"></param>
        /// <param name="signature"></param>
        /// <param name="publicKey"></param>
        /// <returns></returns>
        public static bool VerifyDSA(byte[] message, byte[] signature, AsymmetricKeyParameter publicKey)
        {
            var signer = SignerUtilities.GetSigner("SHA-256withECDSA");
            signer.Init(false, publicKey);
            signer.BlockUpdate(message, 0, message.Length);
            return signer.VerifySignature(signature);
        }
    }
}
